package com.tal.bcc.pad.cloud.coreprogress;

import java.io.IOException;
import java.io.InputStream;

class ProgressInputStream extends InputStream {
    private final InputStream stream;
    private final ProgressCallback listener;
    private long total;
    private long totalRead;

    ProgressInputStream(InputStream stream, ProgressCallback listener, long total) {
        this.stream = stream;
        this.listener = listener;
        this.total = total;
    }

    public int read() throws IOException {
        int read = this.stream.read();
        if (this.total < 0L) {
            this.listener.onProgressChanged(-1L, -1L, -1.0F);
            return read;
        } else {
            if (read >= 0) {
                ++this.totalRead;
                this.listener.onProgressChanged(this.totalRead, this.total, (float)this.totalRead * 1.0F / (float)this.total);
            }

            return read;
        }
    }

    public int read(byte[] b, int off, int len) throws IOException {
        int read = this.stream.read(b, off, len);
        if (this.total < 0L) {
            this.listener.onProgressChanged(-1L, -1L, -1.0F);
            return read;
        } else {
            if (read >= 0) {
                this.totalRead += (long)read;
                this.listener.onProgressChanged(this.totalRead, this.total, (float)this.totalRead * 1.0F / (float)this.total);
            }

            return read;
        }
    }

    public void close() throws IOException {
        if (this.stream != null) {
            this.stream.close();
        }

    }
}